package com.luoye.audiodemo

import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.blankj.utilcode.util.LogUtils

fun Activity.openFragment(fragment: String) {
    startActivity(Intent(this, FragmentActivity::class.java).apply {
        putExtra("fragment", fragment)
    })
}

class FragmentActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_fragment)
        val fragmentName = intent.getStringExtra("fragment")
        LogUtils.e(fragmentName)
        val fragment = Class.forName(fragmentName).newInstance()
        showFragment(fragment as Fragment, supportFragmentManager, R.id.frameBody)
    }
}

fun showFragment(fragment: Fragment, fragmentManager: FragmentManager, id: Int) {

    try {
        val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
        //隐藏所有的那个啥。
        for (fra in fragmentManager.fragments) {
            fragmentTransaction.hide(fra)
        }
        val fragmentByTag: Fragment? = fragmentManager.findFragmentByTag(fragment.javaClass.name)
        if (fragmentByTag != null) {
            fragmentTransaction.show(fragmentByTag)
        } else {

            fragmentTransaction.add(id, fragment, fragment.javaClass.name)
        }
        //添加到返回栈中
        //  fragmentTransaction.addToBackStack(className);
        fragmentTransaction.commitAllowingStateLoss()
    } catch (e: Exception) {
        LogUtils.e(e)
    }

}